package logdump

import (
	"fmt"
	"strings"
	"sync"
	"time"

	"gitee.com/crack007/proxy/src/logserver/model"
	"gitee.com/crack007/proxy/src/logserver/service"

	"gitee.com/crack007/goose/gslog"
)

type logItem struct {
	Arg []interface{}
}

var _logDump *logDump

type logDump struct {
	infoLogQueue  chan *logItem
	warnLogQueue  chan *logItem
	splitInterval int
	splitTag      string
	splitCount    int
	lastDumpAt    time.Time
	lock          sync.Mutex
}

func (s *logDump) ConsumeInfoLog() {
	for mysqlLog := range s.infoLogQueue {
		s.showSplit()
		msg := mysqlLog.Arg[0]
		gslog.Info(msg.(string), mysqlLog.Arg[1:]...)
		service.LogService.PushLog(&model.LogModel{Content: fmt.Sprintf(msg.(string), mysqlLog.Arg[1:]...), Level: "info", Timestamp: int(time.Now().Unix())})
	}
}

func (s *logDump) showSplit() {
	if s.splitInterval > 0 {
		s.lock.Lock()
		defer s.lock.Unlock()
		n := time.Now()
		if int(n.Unix()-s.lastDumpAt.Unix()) > s.splitInterval {
			gslog.Warn("\r\n\r\n%s\r\n", strings.Repeat(s.splitTag, s.splitCount))
		}
		s.lastDumpAt = n
	}
}

func (s *logDump) ConsumeWarnLog() {
	for mysqlLog := range s.warnLogQueue {
		s.showSplit()
		msg := mysqlLog.Arg[0]
		gslog.Warn(msg.(string), mysqlLog.Arg[1:]...)
		service.LogService.PushLog(&model.LogModel{Content: fmt.Sprintf(msg.(string), mysqlLog.Arg[1:]...), Level: "warn", Timestamp: int(time.Now().Unix())})
	}
}

func Init(splitInterval int, splitTag string, splitCount int) {
	_logDump = &logDump{
		infoLogQueue:  make(chan *logItem, 1024),
		warnLogQueue:  make(chan *logItem, 1024),
		splitInterval: splitInterval,
		splitTag:      splitTag,
		splitCount:    splitCount,
	}
	go _logDump.ConsumeInfoLog()
	go _logDump.ConsumeWarnLog()
}

func Warn(args ...interface{}) {
	warnLog := &logItem{}
	warnLog.Arg = args
	_logDump.warnLogQueue <- warnLog
}

func Info(args ...interface{}) {
	debugLog := &logItem{}
	debugLog.Arg = args
	_logDump.infoLogQueue <- debugLog
}
